// 该页面为测试页面，已归类到 test 目录
<template>
  <div class="chat-test-page">
    <h2>AI Chat接口测试（POST流式）</h2>
    <el-input
      v-model="input"
      placeholder="请输入内容..."
      clearable
      style="width: 400px; margin-bottom: 12px"
      @keyup.enter="send"
    />
    <el-button type="primary" :loading="loading" @click="send">发送</el-button>
    <div v-if="messages.length" class="chat-response" style="margin-top: 20px">
      <div v-for="(msg, idx) in messages" :key="idx" class="chat-msg">{{ msg }}</div>
    </div>
    <div v-if="streaming" class="chat-streaming">
      <span>AI正在思考...</span>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { ElMessage } from 'element-plus'

  const input = ref('')
  const messages = ref<string[]>([])
  const loading = ref(false)
  const streaming = ref(false)

  const send = async () => {
    if (!input.value.trim()) {
      ElMessage.warning('请输入内容')
      return
    }
    messages.value = ['']
    loading.value = true
    streaming.value = true
    try {
      const response = await fetch('/api/ai/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ messages: [{ role: 'user', content: input.value }] }),
      })
      if (!response.body) throw new Error('无流式响应')
      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        const chunk = decoder.decode(value, { stream: true })
        console.log('>>>', chunk)
        // 以SSE块为单位处理
        let blocks = chunk.split('"\\n\\n"')

        for (const block of blocks) {
          if (block.startsWith('"data:"')) {
            // 提取data:后内容，去掉多余引号和空白
            let content = block
              .replace('"data:"', '')
              .replace(/\\ndata:/g, '\n')
              .replace(/"/g, '')
            console.log(block, ' -> ', content)
            if (content) {
              messages.value[messages.value.length - 1] += content
            }
          }
        }
      }
      console.log('>>>', messages.value)
    } catch (e) {
      ElMessage.error('请求失败')
      console.error(e)
    } finally {
      loading.value = false
      streaming.value = false
    }
  }
</script>

<style scoped>
  .chat-test-page {
    max-width: 600px;
    margin: 40px auto;
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
  .chat-msg {
    background: #f4f6fa;
    margin-bottom: 8px;
    padding: 8px 12px;
    border-radius: 4px;
    word-break: break-all;
    white-space: pre-line;
  }
  .chat-streaming {
    color: #409eff;
    margin-top: 12px;
  }
</style>
